package com.example.tsbs.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpRequest {

    /**
     * 发送GET请求
     * @param url  "http://api.example.com/data?param1=value1&param2=value2"
     */
    public static String getRequest(String url) {
        try {
//        String url = "http://api.example.com/data?param1=value1&param2=value2";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 设置请求类型
        con.setRequestMethod("GET");

        int responseCode = con.getResponseCode();
        System.out.println("Response Code : " + responseCode);

        // 读取响应
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // 打印结果
        System.out.println(response.toString());
        return response.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "接口调用失败";
        }
    }

    /**
     * 发送POST请求
     * @param url  "http://api.example.com/data"
     */
    public static String postRequest(String url)  {
        try {
//        String url = "http://api.example.com/data";
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            // 设置请求类型
            con.setRequestMethod("POST");
            // 添加请求头
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 发送Post请求
            con.setDoOutput(true);
            OutputStream os = con.getOutputStream();
            byte[] input = "param1=value1&param2=value2".getBytes();
            os.write(input, 0, input.length);
            os.flush();
            os.close();
            int responseCode = con.getResponseCode();
            System.out.println("Response Code : " + responseCode);

            // 读取响应
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 打印结果
            System.out.println(response.toString());
            return response.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "接口调用失败";
        }
    }


}
